import eState from "../Lib/StateMachine/eState";
import G from "../Utilities/Global";
import StateEvent from "../Lib/StateMachine/StateEvent";

/**
 * 动作管理,全局的
 * created by Five on 2018-11-15 11:22:21
 */

export default class AnimationController {
    // 动作控制器,目前不确定具体是什么    
    private _animator: cc.Animation = null;
    // 目标节点
    private _node: cc.Node = null;

    private _isRunning: boolean = false;
    private _state2anim: Map<eState, string>;

    private _currentData: StateEvent = null;

    constructor(node: cc.Node, flex: string) {
        this._node = node;
        this.initMap(flex);
    }

    async initClips() {
        let animator = this._node.getComponent(cc.Animation);
        if (animator == null) {
            animator = this._node.addComponent(cc.Animation);
            await this.addClips(animator, this._state2anim.get(eState.MOVE));
            await this.addClips(animator, this._state2anim.get(eState.IDLE));
            await this.addClips(animator, this._state2anim.get(eState.ATTACK));
        }
        this._animator = animator;
        this._animator.on("finished", this.animationEnd, this);
    }

    async addClips(animator: cc.Animation, clip: string) {
        let srcClip = await G().Res.GetClip(clip) as cc.AnimationClip;
        if (srcClip != null)
            animator.addClip(srcClip);
    }

    stateEnter(data: cc.Event.EventCustom) {
        this.executeAnim(data.detail[0]);
        this._currentData = data.detail[1];
    }

    stateExecute(data: cc.Event.EventCustom) {
        if (this._isRunning)
            return;
        this.executeAnim(data.detail[0]);
        this._currentData = data.detail[1];
    }

    stateExit(data: cc.Event.EventCustom) {
        this._currentData = data.detail[1];
    }

    executeAnim(state: eState) {
        this.play(this._state2anim.get(state));
    }

    initMap(flex: string) {
        this._state2anim = new Map<eState, string>();
        this._state2anim.set(eState.IDLE, flex + "_stand");
        this._state2anim.set(eState.ATTACK, flex + "_attack");
        this._state2anim.set(eState.JUMP, flex + "_jump");
        this._state2anim.set(eState.MOVE, flex + "_walk");
        this._state2anim.set(eState.NONE, "");
        this._state2anim.set(eState.SQAUT, flex + "_sqaut");
        this._state2anim.set(eState.DYING, flex + "_dying");
        this._state2anim.set(eState.DAED, "");
    }

    animationEnd() {
        this._isRunning = false;
        if (this._currentData != null)
            this._currentData.Action(this._currentData.Datas);
    }

    play(act: string) {
        this._isRunning = true;
        if (act != "")
            this._animator.play(act);
        else
            this._animator.play(this._state2anim.get(eState.IDLE));
    }

    pause() {
        this._animator.pause();
    }

    resume() {
        this._animator.resume();
    }
}